﻿using System;
using System.Windows.Browser;

namespace HtmlUtilities
{
    public interface IHtmlPage
    {
        IBrowserInformation BrowserInformation { get; }
        IHtmlDocment Document { get; }
        bool IsEnabled { get; }
        bool IsPopupWindowAllowed { get; }
        IHtmlElement Plugin { get; }
        IHtmlWindow Window { get; }

        IHtmlWindow PopupWindow(Uri uri, string target, HtmlPopupWindowOptions options);
        void RegisterCreateableType(string scriptAlias, Type type);
        void RegisterScriptableObject(string scriptKey, object instance);
        void UnregisterCreateableType(string scriptAlias);
    }

    public class Html : IHtmlPage
    {
        private Html()
        {
        }

        private static readonly IHtmlPage _htmlPage = new Html();
        private static IHtmlPage _testingPage;

        public static IHtmlPage Page
        {
            get
            {
                if (_testingPage != null)
                    return _testingPage;

                return _htmlPage;
            }
        }

        public static void SetHtmlPageForTesting(IHtmlPage testingPage)
        {
            _testingPage = testingPage;
        }

        public IBrowserInformation BrowserInformation
        {
            get { return new BrowserInformationWrapper(HtmlPage.BrowserInformation); }
        }

        public IHtmlDocment Document
        {
            get { return ScriptObjectFactory.GetScriptObject<IHtmlDocment>(HtmlPage.Document); }
        }

        public bool IsEnabled
        {
            get { return HtmlPage.IsEnabled; }
        }

        public bool IsPopupWindowAllowed
        {
            get { return HtmlPage.IsPopupWindowAllowed; }
        }

        public IHtmlElement Plugin
        {
            get { return ScriptObjectFactory.GetScriptObject<IHtmlElement>(HtmlPage.Plugin); }
        }

        public IHtmlWindow Window
        {
            get { return ScriptObjectFactory.GetScriptObject<IHtmlWindow>(HtmlPage.Window); }
        }

        public IHtmlWindow PopupWindow(Uri uri, string target, HtmlPopupWindowOptions options)
        {
            return ScriptObjectFactory.GetScriptObject<IHtmlWindow>(HtmlPage.PopupWindow(uri, target, options));
        }

        public void RegisterCreateableType(string scriptAlias, Type type)
        {
            HtmlPage.RegisterCreateableType(scriptAlias, type);
        }

        public void RegisterScriptableObject(string scriptKey, object instance)
        {
            HtmlPage.RegisterScriptableObject(scriptKey, instance);
        }

        public void UnregisterCreateableType(string scriptAlias)
        {
            HtmlPage.UnregisterCreateableType(scriptAlias);
        }
    }
}
